﻿
using Oracle.ManagedDataAccess.Client;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;


namespace s7nck
{

    public partial class Form1 : Form
    {
        // private System.Threading.Timer _timer = null;//定义一个全局的定时器
        public List<LdMachine> machineList = new List<LdMachine>();
         

        public Socket ncksocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        public Form1()
        {
            InitializeComponent();
            listView1.ContextMenuStrip = contextMenuStrip2;
            contextMenuStrip1.Closed += new ToolStripDropDownClosedEventHandler(contextMenuStrip1_Closed);
        }
        //根据duid更新设备状态和数据项
        public void updateListview1(string status,string itemcount,string guid)
        {
            for (int i = 0; i < listView1.Items.Count; i++)
            {
                if (listView1.Items[i].SubItems[5].Text.Equals(guid))
                {
                    listView1.Items[i].SubItems[3].Text = status;
                    listView1.Items[i].SubItems[4].Text = itemcount;

                }

            }
        }
        
        private void listView1_MouseClick(object sender, MouseEventArgs e)
        {
            //设置启动和停止按钮状态
            if (listView1.SelectedItems.Count > 0)
            {
                foreach (var machine in machineList)
                {

                    if (machine.Guid.Equals(listView1.SelectedItems[0].SubItems[5].Text))
                    {
                        if (machine.StartStatus)
                        {
                            contextMenuStrip1.Items[0].Enabled = false;
                            contextMenuStrip1.Items[1].Enabled = true;

                        }
                        else
                        {
                            contextMenuStrip1.Items[0].Enabled = true;
                            contextMenuStrip1.Items[1].Enabled = false;
                        }
                    }
                }
            }
           
            
            //判断显示哪个strip
            if (listView1.SelectedItems.Count>0)
            {
                if (e.Button == MouseButtons.Right)
                {
                    listView1.ContextMenuStrip = null;
                    contextMenuStrip1.Show(listView1, e.Location);
                    // MessageBox.Show("MouseButton Right Clicked");
                }
            }
           
        }

        void contextMenuStrip1_Closed(object sender, ToolStripDropDownClosedEventArgs e)
        {
            listView1.ContextMenuStrip = contextMenuStrip2;
        }

        private void button1_Click(object sender, EventArgs e)
        {
           /* //socket连接
          //  string ip = textBox1.Text;
          //  int port = Convert.ToInt32(textBox2.Text);
            IPAddress address = IPAddress.Parse(ip);
           // IPEndPoint ipendpoint = new IPEndPoint(address, port);
            // ncksocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            ncksocket.Connect(ipendpoint);

            //s7协议握手
            //s7 握手
            byte[] s1 = new byte[] { 3,0, 0, 0x16, 0x11, 0xe0, 0, 0, 04, 0x30, 0, 0xc1, 2, 4, 0, 0xc2, 02, 0x03, 03, 0xc0, 01, 0x0a };
            ncksocket.Send(s1, s1.Length, SocketFlags.None);
            *//* int   byteCount1 = socketSend.Receive(bytes, 0, socketSend.Available,
                                  SocketFlags.None);*//*
            byte[] message1 = Class1.receibeMessage(ncksocket,22);
            StringBuilder text = new StringBuilder();
            for (int i = 0; i < message1.Length; i++)
            {
                text.Append(message1[i].ToString("x2"));
                text.Append("-");
            }
          //  textBox3.Text += DateTime.Now.ToString() + "  " + text.ToString() + Environment.NewLine;
            Console.WriteLine("接受的内容-----"+ text.ToString()+"-----");

            byte[] ss = new byte[] { 3, 0, 0, 0x19, 2, 0xf0, 0x80, 0x32, 1, 0, 0, 0, 1, 0, 8, 0, 0, 0xf0, 0, 0, 0x64, 0, 0x64, 03, 0xc0 };
            ncksocket.Send(ss, ss.Length, SocketFlags.None);
           

            byte[] message2 = Class1.receibeMessage(ncksocket,25);
            StringBuilder text2 = new StringBuilder();
            for (int i = 0; i < message2.Length; i++)
            {
                text2.Append(message2[i].ToString("x2"));
                text2.Append("-");
            }
           // textBox3.Text += DateTime.Now.ToString() + "  " + text2.ToString() + Environment.NewLine;


            // MessageBox.Show("连接成功！！！"+byteCount1+" "+byteCount2);
            MessageBox.Show("连接成功！！！" + message1.Length + " "*//* + message2.Length*//*);

*/
        }

        private void button3_Click(object sender, EventArgs e)
        {
            StringBuilder textboxShow = new StringBuilder();
            //actspeed
            byte[] actspeedComment = new byte[] { 0x03, 0x00, 0x00, 0x1D, 0x02, 0xF0, 0x80, 0x32, 0x01, 0x00, 0x00, 0x00, 0x14, 0x00, 0x0C, 0x00, 0x00, 0x04, 0x01, 0x12, 0x08, 0x82, 0x41, 0x00, 0x02, 0x00, 0x01, 0x42, 0x01 };
            ncksocket.Send(actspeedComment, actspeedComment.Length, SocketFlags.None);
            //25+8      8个数据byte
            byte[] actspeedResult = Class1.receibeMessage(ncksocket, 33);
          byte[] actspeedBytes =  Commons.getbytes(actspeedResult, 25);
           double actspeedValue = BitConverter.ToDouble(actspeedBytes, 0);
            textboxShow.Append("actspeedValue=" + actspeedValue+"----"+System.DateTime.Now + Environment.NewLine);


            //mode  0:JOG,1:MDA,2:AUTO
            byte[] modeComment = new byte[] { 0x03, 0x00, 0x00, 0x1D, 0x02, 0xF0, 0x80, 0x32, 0x01, 0x00, 0x00, 0x00, 0x14, 0x00, 0x0C, 0x00, 0x00, 0x04, 0x01, 0x12, 0x08, 0x82, 0x21, 0x00, 0x03, 0x00, 0x01, 0x7f, 0x01 };
            ncksocket.Send(modeComment, modeComment.Length, SocketFlags.None);

            byte[] modeResult = Class1.receibeMessage(ncksocket, 25 + 2);
            byte[] modeBytes = Commons.getbytes(modeResult, 25);
            short modeValue = BitConverter.ToInt16(modeBytes, 0);
            textboxShow.Append("modeValue===" + modeValue+"----" + DateTime.Now + Environment.NewLine);


            //execution  程序状态 1 = 中断 2 = 停止 3 = 运行  4 = 等待 5 = 取消
             byte[] executionComment = new byte[] { 0x03, 0x00, 0x00, 0x1D, 0x02, 0xF0, 0x80, 0x32, 0x01, 0x00, 0x00, 0x00, 0x14, 0x00, 0x0C, 0x00, 0x00, 0x04, 0x01, 0x12, 0x08, 0x82, 0x41, 0x00, 0x0d, 0x00, 0x01, 0x7f, 0x01 };
             ncksocket.Send(executionComment, SocketFlags.None);
             byte[] executionResult = Class1.receibeMessage(ncksocket, 25 + 2);
             byte[] executionBytes = Commons.getbytes(executionResult, 25);
             short executionValue = BitConverter.ToInt16(executionBytes,0);
             textboxShow.Append("execution===" + executionValue+"---" + DateTime.Now + Environment.NewLine);

            //program   
            byte[] programComment = new byte[] { 0x03, 0x00, 0x00, 0x1D, 0x02, 0xF0, 0x80, 0x32, 0x01, 0x00, 0x00, 0x00, 0x14, 0x00, 0x0C, 0x00, 0x00, 0x04, 0x01, 0x12, 0x08, 0x82, 0x41, 0x00, 0x23, 0x00, 0x01, 0x7d, 0x01 };
            ncksocket.Send(programComment, SocketFlags.None);
            byte[] programResult = Class1.receibeMessage(ncksocket, 25 + 160);
            byte[] programBytes = Commons.getbytes(programResult, 25);
            string programValue = Encoding.ASCII.GetString(programBytes);
            //切割掉"?"部分
            string[] programValueBytes = programValue.Split('/');
            string programValue3 = programValueBytes[2];


            textboxShow.Append("program==="+ programValue3 + "----"+ DateTime.Now + Environment.NewLine);

            //实际进给
            byte[] actfeedComment = new byte[] { 0x03, 0x00, 0x00, 0x1D, 0x02, 0xF0, 0x80, 0x32, 0x01, 0x00, 0x00, 0x00, 0x14, 0x00, 0x0C, 0x00, 0x00, 0x04, 0x01, 0x12, 0x08, 0x82, 0x41, 0x00, 0x01, 0x00, 0x01, 0x7f, 0x01 };
            ncksocket.Send(actfeedComment, actfeedComment.Length, SocketFlags.None);
            //25+8      8个数据byte
            byte[] actfeedResult = Class1.receibeMessage(ncksocket, 33);
            byte[] actfeedBytes = Commons.getbytes(actfeedResult, 25);
            double actfeedValue = BitConverter.ToDouble(actfeedBytes, 0);
            textboxShow.Append("actfeedValue=" + actfeedValue + "----" + System.DateTime.Now + Environment.NewLine);
            //主轴倍率
            byte[] speedovrComment = new byte[] { 0x03, 0x00, 0x00, 0x1D, 0x02, 0xF0, 0x80, 0x32, 0x01, 0x00, 0x00, 0x00, 0x14, 0x00, 0x0C, 0x00, 0x00, 0x04, 0x01, 0x12, 0x08, 0x82, 0x41, 0x00, 0x04, 0x00, 0x01, 0x72, 0x01 };
            ncksocket.Send(speedovrComment, speedovrComment.Length, SocketFlags.None);
            //25+8      8个数据byte
            byte[] speedovrResult = Class1.receibeMessage(ncksocket, 33);
            byte[] speedovrBytes = Commons.getbytes(speedovrResult, 25);
            double speedovrdValue = BitConverter.ToDouble(speedovrBytes, 0);
            textboxShow.Append("speedovrdValue=" + speedovrdValue + "----" + System.DateTime.Now + Environment.NewLine);
            //进给倍率
            byte[] feedovrComment = new byte[] { 0x03, 0x00, 0x00, 0x1D, 0x02, 0xF0, 0x80, 0x32, 0x01, 0x00, 0x00, 0x00, 0x13, 0x00, 0x0C, 0x00, 0x00, 0x04, 0x01, 0x12, 0x08, 0x82, 0x41, 0x00, 0x03, 0x00, 0x01, 0x7F, 0x01 };
            ncksocket.Send(feedovrComment, feedovrComment.Length, SocketFlags.None);
            //25+8      8个数据byte
            byte[] feedovrResult = Class1.receibeMessage(ncksocket, 33);
            byte[] feedovrBytes = Commons.getbytes(feedovrResult, 25);
            double feedovrdValue = BitConverter.ToDouble(feedovrBytes, 0);
            textboxShow.Append("feedovrdValue=" + feedovrdValue + "----" + System.DateTime.Now + Environment.NewLine);


            // textBox3.Text = textboxShow.ToString();
            Console.WriteLine(textboxShow.ToString());
           
        }

        //test 
        private void button4_Click(object sender, EventArgs e)
        {
            updateListview1("dfsd", "3","1234");

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //创建设备，放到list中
            //遍历文件夹中的xml文件
            string s = null;
            DirectoryInfo d = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory + "config//");
            FileInfo[] files = d.GetFiles("*.xml");
            List<string> lstr = new List<string>();

            foreach (FileInfo file in files)

            {
                s = file.Name;
                lstr.Add(s);

            }

            foreach (var item in lstr)
            {
               Dictionary<string,Dictionary<string,Dictionary<string,string>>> dicttemp = Commons.getAdapterXml(AppDomain.CurrentDomain.BaseDirectory + "config//" + item);
                string filename = item.Replace(".xml", "");
                LdMachine machine = new LdMachine();

                machine.Ip = dicttemp["Connect"]["ip"]["val"];
                machine.Port = dicttemp["Connect"]["port"]["val"];
                machine.MachineName = dicttemp["Connect"]["name"]["val"];
                machine.Guid = dicttemp["Connect"]["guid"]["val"];
                machineList.Add(machine);


                //填充listview

                ListViewItem items = new ListViewItem(machine.Ip);
                string[] fitrst = new string[] {  machine.Port, machine.MachineName, "stop", "0", machine.Guid };
                items.SubItems.AddRange(fitrst);
                listView1.Items.Add(items);

            }

           


        }


       

        //选中设备启动采集
        private void 启动ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //找出选择的设备
            foreach (var machine in machineList)
            {
                if (machine.Guid.Equals(listView1.SelectedItems[0].SubItems[5].Text))
                {
                    machine.Timer = new System.Threading.Timer(new TimerCallback(readDataTimer), machine, 5000, 5000);
                    machine.StartStatus = true;
                    listView1.SelectedItems[0].SubItems[3].Text = "running";

                }
            }

            


        }

        //采集方法readdata
        public void readDataTimer(object obj)
        {
           
            LdMachine machine = (LdMachine)obj;
                if (Commons.Ping(machine.Ip, 1000, 10))
                {
                       
                    machine.Ncksocket.Dispose();
                             machine.connectMachine();
                                machine.ConnectStatus = true;
                      

                    

                }
                else
                {
                    machine.ConnectStatus = false;
                machine.Cache["mode"] = "UNAVAILABLE";
                machine.Cache["execution"] = "UNAVAILABLE";
                machine.Cache["program"] = "UNAVAILABLE";
                machine.Cache["pathFeedrate"] = "UNAVAILABLE";
                machine.Cache["pathSvalue"] = "UNAVAILABLE";
                machine.Cache["feedOvr"] = "UNAVAILABLE";
                machine.Cache["speedOvr"] = "UNAVAILABLE";


                return;

                }
            
            //读取数据mode
            byte[] mode = new byte[] { 0x03, 0x00, 0x00, 0x1D, 0x02, 0xF0, 0x80, 0x32, 0x01, 0x00, 0x00, 0x00, 0x14, 0x00, 0x0C, 0x00, 0x00, 0x04, 0x01, 0x12, 0x08, 0x82, 0x21, 0x00, 0x03, 0x00, 0x01, 0x7f, 0x01
  };
          string modeResult =  machine.readData(mode, 25 + 2, "short");
            machine.Cache["mode"] = modeResult;
            //machine.Cache.AddOrUpdate("mode", modeResult,)

            //read execution
            byte[] execution = new byte[] { 0x03, 0x00, 0x00, 0x27, 0x02, 0xF0, 0x80, 0x32, 0x01, 0x00, 0x00, 0x00, 0x14, 0x00, 0x16, 0x00, 0x00, 0x04, 0x02, 0x12, 0x08, 0x82, 0x41, 0x00, 0x0d, 0x00, 0x01, 0x7F, 0x01 };
            string executionResult = machine.readData(execution, 25 + 2, "short");
            machine.Cache["execution"] = executionResult;

            //read program
            /*byte[] program = new byte[] { 0x03, 0x00, 0x00, 0x1D, 0x02, 0xF0, 0x80, 0x32, 0x01, 0x00, 0x00, 0x00, 0x14, 0x00, 0x0C, 0x00, 0x00, 0x04, 0x01, 0x12, 0x08, 0x82, 0x41, 0x00, 0x23, 0x00, 0x01, 0x7d, 0x01 };
            string programResult = machine.readData(program, 25 + 160, "string");
            machine.Cache["program"] = programResult;*/


            //read pathFeedrate
            byte[] pathFeedrate = new byte[] { 0x03, 0x00, 0x00, 0x1D, 0x02, 0xF0, 0x80, 0x32, 0x01, 0x00, 0x00, 0x00, 0x14, 0x00, 0x0C, 0x00, 0x00, 0x04, 0x01, 0x12, 0x08, 0x82, 0x41, 0x00, 0x01, 0x00, 0x01, 0x7f, 0x01 };

            string pathFeedrateResult = machine.readData(pathFeedrate, 25 + 8, "double");

            machine.Cache["pathFeedrate"] = pathFeedrateResult;

            

            //read path_svalue
            byte[] pathSvalue = new byte[] { 0x03, 0x00, 0x00, 0x1D, 0x02, 0xF0, 0x80, 0x32, 0x01, 0x00, 0x00, 0x00, 0x14, 0x00, 0x0C, 0x00, 0x00, 0x04, 0x01, 0x12, 0x08, 0x82, 0x41, 0x00, 0x02, 0x00, 0x01, 0x42, 0x01 };
            string pathSvalueResult = machine.readData(pathSvalue, 25 + 8, "double");
            machine.Cache["pathSvalue"] = pathSvalueResult;

            //read feed_ovr
            byte[] feedOvr = new byte[] { 0x03, 0x00, 0x00, 0x1D, 0x02, 0xF0, 0x80, 0x32, 0x01, 0x00, 0x00, 0x00, 0x13, 0x00, 0x0C, 0x00, 0x00, 0x04, 0x01, 0x12, 0x08, 0x82, 0x41, 0x00, 0x03, 0x00, 0x01, 0x7F, 0x01 };
            string feedOvrResult = machine.readData(feedOvr, 25 + 8, "double");
            machine.Cache["feedOvr"] = feedOvrResult;

            //read sspeedovr
            byte[] speedOvr = new byte[] { 0x03, 0x00, 0x00, 0x1D, 0x02, 0xF0, 0x80, 0x32, 0x01, 0x00, 0x00, 0x00, 0x14, 0x00, 0x0C, 0x00, 0x00, 0x04, 0x01, 0x12, 0x08, 0x82, 0x41, 0x00, 0x04, 0x00, 0x01, 0x72, 0x01 };
            string speedOvrResult = machine.readData(speedOvr, 25 + 8, "double");
            machine.Cache["speedOvr"] = speedOvrResult;


            this.Invoke(new Action<string, string, string>(updateListview1), new object[] { "运行", "6", machine.Guid });

        }

        //停止设备采集
        private void 停止ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            foreach (var machine in machineList)
            {
                if (machine.Guid.Equals(listView1.SelectedItems[0].SubItems[5].Text))
                {
                    machine.Timer.Dispose();
                    machine.Ncksocket.Dispose();
                    
                    machine.ConnectStatus = false;
                    machine.StartStatus = false;
                    machine.Cache["mode"]= "0";
                    machine.Cache["execution"] = "0";
                    machine.Cache["program"] = "0";
                    machine.Cache["pathFeedrate"] = "0";
                    machine.Cache["pathSvalue"] = "0";
                    machine.Cache["feedOvr"] = "0";
                    machine.Cache["speedOvr"] = "0";

                }
            }
            listView1.SelectedItems[0].SubItems[3].Text = "stop";
            listView1.SelectedItems[0].SubItems[4].Text = "0";


        }

        private void 查看数据项ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ShowDataWinform ss = new ShowDataWinform();
            ss.showmachineIP(listView1.SelectedItems[0].SubItems[2].Text, listView1.SelectedItems[0].SubItems[0].Text);
            foreach (var machine in machineList)
            {
                if (listView1.SelectedItems[0].SubItems[5].Text.Equals(machine.Guid))
                {
                    ss.cache = machine.Cache;
                }
            }
            
            ss.ShowDialog();
        }

        System.Threading.Timer odbcTimer;
        //启动odbc
        private void button5_Click(object sender, EventArgs e)
        {


            odbcTimer = new System.Threading.Timer(odbcOracle);
            odbcTimer.Change(1000, 1000);
            button6.Enabled = true;
            button5.Enabled = false;
            label5.Text = "running";


        }


        public void odbcOracle(object obj)
        {

            OracleConnection conn = null;
            try
            {
                //获取与数据库的连接对象
                conn = new OracleConnection();
                //绑定连接字符串
                conn.ConnectionString = "Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=127.0.0.1)(PORT=1521)) (CONNECT_DATA=(SERVICE_NAME=orcl)));Persist Security Info=True;User ID=mdc_pro;Password=lmdc;";
                //开启连接
                conn.Open();

                //创建操作对象
                OracleCommand cmd = conn.CreateCommand();
                foreach (var machine in machineList)
                {
                    foreach (var item in machine.Cache)
                    {
                        try
                        {
                            cmd.CommandText = $"update S7BCNET set VALUE = '{item.Value}',UPDATETIME = TO_DATE('{DateTime.Now}','yyyy-MM-dd hh24:mi:ss') WHERE KEY = '{item.Key}'and MACHINENAME = '{machine.MachineName}'";
                            cmd.CommandType = CommandType.Text;
                            //执行
                            cmd.ExecuteNonQuery();
                        }
                        catch (Exception ex)
                        {

                            LogHelper.WriteLog(ex.Message, ex);
                        }

                    }

                }


            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex.Message, ex);
            }
            finally
            {
                //关闭连接
                conn.Close();
            }
        }

        private void button6_Click(object sender, EventArgs e)
        {
            odbcTimer.Dispose();
            button5.Enabled = true;
            button6.Enabled = false;
            label5.Text = "stop";

        }
    }
}
